from django.shortcuts import render
from django.views.generic import View, ListView, DetailView
# Create your views here.
from user_info.models import *
from django.http import *
from django.core.paginator import Paginator
from Django_api.settings import BASE_DIR
from product.models import *

def check_user_exist(name):
    try:
        user = User.objects.get(name=name)
        if user:
            return True
        else:
            return False
    except Exception:
        return False


# 查询商品
class GetProductList(View):
    def get(self, request, *args, **kwargs):

        page = self.request.GET.get('page')
        product_list = Product.objects.all()
        if not page:
            page = 1
        pag = Paginator(product_list, 10)
        if int(page) > pag.num_pages:
            return JsonResponse({"status_num": 1, 'massage': 'page_num off page_range!!'})
        product_list = pag.page(int(page))

        product_massage_dic = []
        for product in product_list:
            dic = {}
            dic['id'] = product.id
            dic['name'] = product.product_name
            dic['prize'] = product.prize
            dic['sell_num'] = product.sell_num
            # dic['img'] = product.img.path.split(BASE_DIR)[-1].split('static')[-1].replace(r'\\', '/')
            dic['img'] = ['http://127.0.0.1:8070/image/' + product.img.name]
            if product.num > 0:
                dic['num'] = True
            product_massage_dic.append(dic)
        if product_list.has_previous():
            previous_page = 0
        else:
            previous_page = 1

        if product_list.has_next():
            next_page = 0
        else:
            next_page = 1
        return JsonResponse({'product_massage': product_massage_dic, 'page': page, 'previous_page': previous_page,
                             'next_page': next_page})


# 查询所有商品
class Detail(View):
    def get(self, request, *args, **kwargs):
        id = int(self.request.GET.get('id'))
        try:
            dic = {}
            product = Product.objects.get(pk=id)
            dic['name'] = product.product_name
            dic['prize'] = product.prize
            dic['img'] = ['http://127.0.0.1:8070/image/' + product.img.name]
            return JsonResponse({'massage': dic})
        except Exception:
            print("报错!!!")


# 查询用户订单
class checkOrders(View):
    def get(self, request, *args, **kwargs):
        username = self.request.GET.get('name')
        if username:
            # 关联查询
            try:
                user = User.objects.get(name=username)
                product_list = Order.objects.filter(user=user)
                print(product_list)
                return HttpResponse('ok')
            except Exception:
                pass
        else:
            return  JsonResponse({'status_num': 1, 'massage': 'plase give username massage'})